import { RootState } from '@/models/index';
import { ICarousel } from '@/models/home';
import { hp, viewportWidth, wp } from '@/utils/index';
import React from 'react';
import { Image, StyleSheet, View } from 'react-native';
import SnapCarousel, { AdditionalParallaxProps, Pagination, ParallaxImage } from 'react-native-snap-carousel';
import { connect, ConnectedProps } from 'react-redux';



const sliderWidth = viewportWidth;
const sideWidth = wp(90);
export const sideHeight = hp(26);
const itemWidth = sideWidth + wp(2) * 2;



const mapStateToProps = ({ home, loading }: RootState) => ({
  data: home.carousels,
  activeCarouselIndex: home.activeCarouselIndex,
});

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
  
}

class Carousel extends React.Component<IProps> {



  onSnapToItem = (index: number) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'home/setState',
      payload: {
        activeCarouselIndex: index,
      }
    });
  }


  renderItem = ({item}: {item: ICarousel}, parallaxProps?: AdditionalParallaxProps) => {
    return (
      <ParallaxImage 
        source={{uri: item.image}} 
        style={styles.image}
        containerStyle={styles.imageContainer}
        {...parallaxProps}
        parallaxFactor={0.8}
        showSpinner
        spinnerColor="rgba(0, 0, 0, 0.35)"
        
      />
    );
  }

  get pagination() {
    const {data, activeCarouselIndex} = this.props;
    return (
      <View style={styles.paginationWapper}>
        <Pagination 
          dotsLength={data.length}
          activeDotIndex={activeCarouselIndex}
          containerStyle={styles.paginationContainer}
          dotContainerStyle={styles.dotContainer}
          dotStyle={styles.dot}
          inactiveDotScale={0.7}
          inactiveDotOpacity={0.4}
        />
      </View>
    );
  }

  render() {
    const {data} = this.props;
    return (
      <View>
        <SnapCarousel 
          data={data} 
          renderItem={this.renderItem }
          sliderWidth={sliderWidth}
          itemWidth={itemWidth}
          hasParallaxImages
          loop
          autoplay
          onSnapToItem={this.onSnapToItem}
        />
        {this.pagination}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  
  imageContainer: {
    width: itemWidth,
    height: sideHeight,
    borderRadius: 8,
  },
  image: {
    ...StyleSheet.absoluteFillObject,
    resizeMode: 'contain'
  },
  paginationWapper: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  paginationContainer: {
    position: 'absolute',
    top: -20,
    backgroundColor: 'rgba(0, 0, 0, 0.35)',
    paddingHorizontal: 3,
    paddingVertical: 4, 
    borderRadius: 8,

  },
  dotContainer: {
    marginHorizontal: 6, 

  }, 
  dot: {
    width: 6, 
    height: 6, 
    borderRadius: 3,
    backgroundColor: 'rgba(255, 255, 255, 0.92)',

  }
});

export default connector(Carousel);